package wotd.web;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.Enumeration;
import java.util.logging.Level;
import java.util.logging.Logger;

import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.google.appengine.repackaged.com.google.common.util.Base64DecoderException;

@SuppressWarnings("serial")
public class FacebookServlet extends HttpServlet {
	private static final Logger LOG = Logger.getLogger(FacebookServlet.class.getName());
	
	public void doGet(HttpServletRequest req, HttpServletResponse resp) throws IOException {
		doPost(req, resp);
	}
	
	public void doPost(HttpServletRequest req, HttpServletResponse resp) throws IOException {
		if (LOG.isLoggable(Level.FINE)) {
			for (@SuppressWarnings("unchecked") Enumeration<String> i = req.getParameterNames(); i.hasMoreElements(); ) {
				String name = i.nextElement();
				LOG.fine(name + " = " + req.getParameter(name));
			}
		}

		resp.setContentType("text/html");
		resp.setStatus(HttpServletResponse.SC_OK);
		
		PrintWriter pw = resp.getWriter();
		
		String user = req.getParameter("signed_request");
		String error = req.getParameter("error");
		if (error != null) {
			String desc = req.getParameter("error_description");
			LOG.info("Authorization was denied: " + desc);
			
			pw.println("error");
			
		} else if (user != null) {
			try {
				FacebookUser fbUser = new FacebookUser(user);
			} catch (Base64DecoderException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			
		}
//		
//		
//		if (param == null) {
//			// need to authenticate
//			String redir = URLEncoder.encode(req.getRequestURL().append("?").append(req.getQueryString()).toString(), "UTF-8");
//		    String authUrl = "https://www.facebook.com/dialog/oauth?client_id=225800847430345&redirect_uri=" + redir;
//
//			pw.println("<script>top.location.href='" + authUrl + "'</script>");
//		} else {
//			pw.println("Hello " + param);
//		}
		
		pw.flush();
	}
}
